<template>
  <el-dialog
    v-model="visible"
    width="420px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    center
    class="rounded-xl overflow-hidden"
  >
    <div class="text-center mb-8">
      <h3 class="text-2xl font-semibold text-gray-800 mb-2">云端账号登录</h3>
      <!-- <p class="text-sm text-gray-500">请输入您的云端账号信息</p> -->
      <div class="text-center text-sm text-gray-500">
        没有账号？ <span class="text-blue-500 cursor-pointer" @click="onRegister">前去注册账号</span>
      </div>
    </div>

    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="0" class="space-y-5 p-x-5">
      <el-form-item prop="account" class="mb-10">
        <el-input v-model="formData.account" placeholder="请输入账号" clearable size="large" autocomplete="off" @keyup.enter="onLogin">
          <template #prefix>
            <el-icon class="text-gray-400"><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password" class="mb-10">
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          show-password
          clearable
          size="large"
          autocomplete="new-password"
          @keyup.enter="onLogin"
        >
          <template #prefix>
            <el-icon class="text-gray-400"><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-center gap-4 py4">
        <el-button size="large" class="min-w-24 rounded-lg" @click="onCancel">取消</el-button>
        <el-button type="primary" :loading="loading" size="large" class="min-w-200px rounded-lg" @click="onLogin">登录</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSiteMsgByLoginUser } from '@/api/cloud/cloud'

defineOptions({
  name: 'DkCloudLogin'
})

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据 - 确保初始值为空字符串
const formData = reactive({
  account: '',
  password: ''
})

// 表单验证规则
const formRules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 清空表单数据
const clearFormData = () => {
  formData.account = ''
  formData.password = ''
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 显示弹窗
const show = () => {
  // 先清空表单数据
  clearFormData()
  visible.value = true
}

// 隐藏弹窗
const hide = () => {
  visible.value = false
  // 隐藏时也清空表单
  formData.account = ''
  formData.password = ''
}

// 登录方法
const onLogin = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 先显示确认弹窗
    await ElMessageBox.confirm('当前将绑定该站点，如果没有站点将自动新建站点', '确认登录', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    })

    // 用户确认后开始登录
    loading.value = true
    const res = await getSiteMsgByLoginUser(formData.account, formData.password)
    console.log(res)

    if (res.data) {
      ElMessage.success('登录成功')

      // 隐藏登录弹窗
      hide()

      // 触发登录成功事件
      emit('success', res.data)
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消登录
      console.log('用户取消登录')
    } else {
      console.error('登录失败:', error)
      ElMessage.error(error.msg || '登录失败')
    }
  } finally {
    loading.value = false
  }
}

// 注册方法
const onRegister = () => {
  window.open('http://www.dkyx.cc', '_blank')
}

// 取消登录
const onCancel = () => {
  hide()
  emit('cancel')
}

// 定义事件
const emit = defineEmits(['success', 'cancel'])

// 暴露方法给父组件
defineExpose({
  show,
  hide
})
</script>
